const imagePluginTmpl = require("./tmpl/build/template");
require("./sass/style.scss");
const defaultImage = require("../../img/default.png");

/**
 * config  {
 *      is_upload: false,
 *      container: "",
 *      url: "",
 *      width: "",
 *      height: "",
 *      src: "",
 *      id: "",
 *      autoUpload: false,
 *      eventHandler: {
 *          upload: function(form){
 *              
 *          },
 *          error: function(err){
 *              
 *          },
 *          success: function(data){
 *              
 *          }
 *      }
 * }
 */
class ImagePlugin {
    constructor (config) {
        this.container = config.container;
        this.is_upload = config.is_upload;
        this.url = config.url || null;
        this.width = config.width;
        this.height = config.height;
        this.src = config.src || defaultImage;
        this.eventHandler = config.eventHandler;
        this.autoUpload = config.autoUpload || false;

        this.image = null;
        this.render();
        this.bindEvent();
    }

    render () {
        var html = imagePluginTmpl("image", {
            src: this.src,
            width: this.width,
            height: this.height
        });
        $(this.container).html(html);
    }

    /**
     * 检查文件类型
     */
    checkImageType (file) {
        var allowedFileTypes = ["image/png", "image/jpeg"];
        if(allowedFileTypes.indexOf(file.type) > -1){
            return true;
        }
        return false;
    }

    /**
     * 检查图片大小
     */
    checkImageSize (file){
        const MAX_SIZE = 500000;
        if(file.size > MAX_SIZE){
            return false;
        }else{
            return true;
        }
    }

    checkImage (file){
        var $imageDom = $(this.container).find("[data-image-uploader]");
        if(!this.checkImageType(file)){
            $imageDom.attr("data-content", "图片格式不正确, 请用 jpg 或 png").popover("show");
            return false;
        }else if(!this.checkImageSize(file)){
            $imageDom.attr("data-content", "图片应小于500KB").popover("show");
            return false;
        }else{
            this.image = file;
            return true;
        }
    }

    clearSrc () {
        var $imageDom = $(this.container).find("[data-image-uploader]");
        $imageDom.attr("src", defaultImage);
    }

    bindEvent () {
        var that = this;
        var $imageDom = $(this.container).find("[data-image-uploader]");
        if(this.is_upload){
            $imageDom.unbind("click").bind("click", function(){
                $(this).siblings("input[type=file]").trigger("click");
            });
            $(this.container).find("input[type=file]").off("change").on("change", function(){
                var files = this.files;
                if(files && files.length && that.checkImage(files[0])){
                    that.image = files[0];
                    if(that.autoUpload){
                        that.upload();
                    }else{
                        that.showFile(files[0]);
                    }
                }else{
                    that.image = null;
                }
            });
            $imageDom.unbind("mouseover").bind("mouseover", function(){
                $(this).removeClass("blur").addClass("blur");
            });
            $imageDom.unbind("mouseout").bind("mouseout", function(){
                $(this).removeClass("blur");
            });
        }
    }

    showFile (image) {
        var reader = new FileReader();
        reader.onload = (e) => {
            var src = e.target.result;
            var $imageDom = $(this.container).find("[data-image-uploader]");
            $imageDom.popover("destroy").attr("data-content", "").attr("src", src);
        };
        reader.readAsDataURL(image);
    }

    upload () {
        
        if(!this.image){
            $(this.container).find("[data-image-uploader]").attr("data-content", "请上传图片").popover("show");
            return;
        }

        var formData = new FormData();
        formData.append("image", this.image);
        if(typeof this.eventHandler.upload === "function"){
            if(!this.eventHandler.upload(formData)){
                return;
            }
        }
        $.ajax({
            url: this.url,
            type: "POST",
            cache: false,
            data: formData,
            processData: false,
            contentType: false
        }).done((res)=>{
            if(typeof this.eventHandler.success === "function"){
                this.eventHandler.success.call(this, res);
            }
        }).catch((err)=>{
            console.error(err);
            if(typeof this.eventHandler.error === "function"){
                this.eventHandler.success.call(this, err);
            }
        });
    }

    /**
     * html 重新绘制后，重新恢复事件
     */
    resume (is_upload) {
        this.is_upload = is_upload;
        this.bindEvent();
    }

}

export default ImagePlugin;